"use strict";
cc._RF.push(module, 'a07bfnRZR1Pioq8UW2PE02V', 'ttApi');
// scripts/engines/services/miniGameContent/tt/ttApi.ts

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var miniApp_1 = require("../miniApp");
var gameConfig_1 = require("../../../configs/gameConfig");
var miniParam_1 = require("../miniParam");
var data_control_1 = require("../../../libs/data_control");
var gameEngine_1 = require("../../../gameEngine");
var tt = window['tt'];
var TtApi = /** @class */ (function (_super) {
    __extends(TtApi, _super);
    function TtApi() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        //神奇的方块字
        // protected m_appId: string = 'tt52de2463cde692fe02';//小小运动员
        _this.m_appId = 'tt9870eecd0743573702';
        _this.m_secret = '02049ac4a77c4344b568f2ddc850443e4ed7e32b';
        _this.m_adUnitId = '1854f267603j8nv7jk';
        _this.m_adUnitIdList = ['1854f267603j8nv7jk', '1854f267603j8nv7jk', '1854f267603j8nv7jk'];
        _this.m_BannerId = "1n8t3fst2tro0e3okn";
        _this.m_InsertId = "7leon10m65h10ifea0";
        // 老乡你要啥
        // protected m_appId: string = 'tt3a5c4ce1a56771f4';
        // protected m_secret: string = '480928071e1cc3f2cdbda01ea2d174441e2f880c';
        // //
        // protected m_adUnitId: string = '11flm74jfpgml93lhhb';
        // protected m_adUnitIdList: string[] = ['11flm74jfpgml93lhhb'];
        // protected m_BannerId: string = "13h3c9a8a346m3i82ca"
        // protected m_InsertId: string = "1mm9mdb790h929g3waj"
        // 愤怒的黄瓜
        // protected m_appId: string = 'tt1fed695080d61c40';
        // protected m_secret: string = '5aac06c0d4536ed8ad966881d38704e93c465d5a';
        // //
        // protected m_adUnitId: string = '3chdculk0porbe6q7e';
        // protected m_adUnitIdList: string[] = ['3chdculk0porbe6q7e'];
        // protected m_BannerId: string = "tohunsff53qi4uuf8p"
        // protected m_InsertId: string = "1j8jdimg9hbka58cji"
        //
        _this.m_accessToken = null;
        //录屏管理器
        _this.m_gameRecorderManager = null;
        //录屏文件保存完地址
        _this.m_gameRecordVideoUrl = null;
        //视频广告组件
        _this.m_videoAd = null;
        //录音管理器
        _this.m_soundRecordManager = null;
        //音频文件
        _this.m_lastRecordSoundPath = null;
        _this.m_BannerAd = null;
        _this.bannerSuccess = true;
        //错误回调监听
        _this.OnVideoAdErrorCallback = null;
        _this.wasVideo = false;
        _this.m_gameRecordTimeNow = 0;
        _this.m_localInBlockCity = false;
        return _this;
    }
    TtApi.prototype.drawHead = function (headUrl) {
        return;
    };
    TtApi.prototype.fullScreenVideo = function () {
        return;
    };
    TtApi.prototype.WidgetfullScreen = function () {
        return;
    };
    //
    TtApi.prototype.getUserInfo = function (params) {
        tt.getUserInfo(params);
    };
    TtApi.prototype.showToast = function (params) {
        tt.showToast(params);
    };
    TtApi.prototype.showLoading = function (params) {
        tt.showLoading(params);
    };
    TtApi.prototype.showModal = function (params) {
        tt.showModal(params);
    };
    TtApi.prototype.hideLoading = function () {
        tt.hideLoading();
    };
    TtApi.prototype.getSystemInfoSync = function () {
        return tt.getSystemInfoSync();
    };
    TtApi.prototype.preCreateUnits = function () {
        this.m_gameRecorderManager = tt.getGameRecorderManager();
        this.CheckLocalToBlockCityList();
        //
        tt.onMemoryWarning(function () {
            // this.showToast({title: '内存不足'});
            tt.triggerGC();
        });
    };
    TtApi.prototype.onShareAppMessageGetReward = function (successCallback, errorCallback, completeCallback, isNeedModal) {
        var _this = this;
        //
        var shareAppRewardFunction = function () {
            tt.shareAppMessage({
                templateId: "2w1ji856pahdij2f29",
                query: "",
                success: function () {
                    console.log("tt 分享成功");
                    var shareResult = miniParam_1.getLookVideoFailShareReportData('分享成功');
                    _this.reportAnalytics(shareResult.key, shareResult.obj);
                    successCallback();
                    completeCallback && completeCallback();
                },
                fail: function (e) {
                    console.log("tt 分享失败");
                    var shareResult = miniParam_1.getLookVideoFailShareReportData('分享失败');
                    _this.reportAnalytics(shareResult.key, shareResult.obj);
                    errorCallback(e);
                    completeCallback && completeCallback();
                },
            });
        };
        //
        if (isNeedModal) {
            console.log("tt 拉起分享");
            var shareResult = miniParam_1.getLookVideoFailShareReportData('拉起分享');
            this.reportAnalytics(shareResult.key, shareResult.obj);
            this.showModal({
                title: '游戏奖励',
                content: '视频拉取失败,分享游戏也可领取视频奖励',
                confirmText: '分享',
                showCancel: true,
                success: function (info) {
                    console.log('tt 分享success');
                    if (info.confirm) {
                        shareAppRewardFunction();
                    }
                    else {
                        errorCallback(null);
                        completeCallback();
                    }
                },
            });
        }
        else {
            shareAppRewardFunction();
        }
    };
    TtApi.prototype.createMoreGameBtn = function () {
        //  按钮类型为image
        var buttonWithImage = tt.createMoreGamesButton({
            type: "text",
            style: {
                left: 120,
                top: 400,
                width: 120,
                height: 100,
                backgroundColor: "#ffffff",
                borderColor: "#ffff00",
                borderWidth: 10,
                borderRadius: 10,
                textAlign: "left",
                fontSize: 13,
                lineHeight: 50,
                textColor: "#000000",
            },
            text: "text的button",
            actionType: "box",
            appLaunchOptions: [
                {
                    appId: this.m_appId,
                    query: tt.getLaunchOptionsSync().query,
                    extraData: {},
                },
            ],
            onNavigateToMiniGameBox: function (res) {
                console.log("跳转到小游戏盒子", res);
            },
        });
        var handler = function () {
            console.log("点击更多游戏按钮");
        };
        // 取消监听点击更多游戏按钮事件
        buttonWithImage.offTap(handler);
        // 监听点击更多游戏按钮事件
        buttonWithImage.onTap(handler);
        // 显示更多游戏按钮
        buttonWithImage.show();
        // // 隐藏更多游戏按钮
        //         buttonWithImage.hide();
        // // 销毁更多游戏按钮
        //         buttonWithImage.destroy();
        // const buttonWithText = tt.createMoreGamesButton({
        //     type: "text",
        //     style: {
        //         left: 120,
        //         top: 400,
        //         width: 120,
        //         height: 100,
        //         backgroundColor: "#ffffff",
        //         borderColor: "#ffff00",
        //         borderWidth: 10,
        //         borderRadius: 10,
        //         textAlign: "left",
        //         fontSize: 13,
        //         lineHeight: 50,
        //         textColor: "#000000",
        //     },
        //     text: "text的button",
        //     actionType: "box",
        //     appLaunchOptions: [
        //         {
        //             appId: this.m_appId,
        //             query: tt.getLaunchOptionsSync().query,
        //             extraData: {},
        //         },
        //         // {...}
        //     ],
        //     onNavigateToMiniGameBox(res) {
        //         console.log("跳转到小游戏盒子", res);
        //     },
        // });
    };
    TtApi.prototype.showInterstitialAd = function (onAdClose, onFailed) {
        if (tt) {
            console.log("加抖音 插屏 广告");
            var interstitialAd_1 = tt.createInterstitialAd({
                adUnitId: this.m_InsertId,
            });
            interstitialAd_1.load();
            interstitialAd_1.onLoad(function () {
                console.warn('插屏广告 加载完成');
                interstitialAd_1.show().catch(function (err) {
                    console.warn('插屏广告 显示失败 ：' + JSON.stringify(err));
                    interstitialAd_1.destroy();
                    interstitialAd_1 = null;
                    if (onFailed) {
                        onFailed();
                    }
                });
            });
            interstitialAd_1.onError(function (err) {
                console.warn('插屏广告 加载失败' + JSON.stringify(err));
                interstitialAd_1.destroy();
                interstitialAd_1 = null;
                if (onFailed) {
                    onFailed();
                }
            });
            interstitialAd_1.onClose(function () {
                console.warn('插屏广告 关闭');
                if (interstitialAd_1 != null) {
                    interstitialAd_1.destroy();
                    interstitialAd_1 = null;
                }
                if (onAdClose) {
                    onAdClose();
                }
            });
        }
        else {
            onAdClose();
        }
    };
    TtApi.prototype.showBannerAD = function (node) {
        var _this = this;
        var _a = tt.getSystemInfoSync(), windowWidth = _a.windowWidth, windowHeight = _a.windowHeight;
        var targetBannerAdWidth = 200;
        if (this.m_BannerAd && this.bannerSuccess == false) {
            this.m_BannerAd.destroy();
            this.m_BannerAd = null;
        }
        if (this.m_BannerAd) {
            this.m_BannerAd.show()
                .then(function () {
                console.log("广告显示成功");
            })
                .catch(function (err) {
                console.log("广告组件出现问题", err);
            });
            return;
        }
        this.bannerSuccess = true;
        this.m_BannerAd = tt.createBannerAd({
            adUnitId: this.m_BannerId,
            adIntervals: 30,
            style: {
                width: targetBannerAdWidth,
                top: windowHeight - (targetBannerAdWidth / 16) * 9,
            }
        }); //创建
        this.m_BannerAd.onResize(function (size) {
            console.log(size.width, size.height, "banner长宽");
            _this.m_BannerAd.style.top = windowHeight - size.height;
            _this.m_BannerAd.style.left = (windowWidth - size.width) / 2;
        });
        this.m_BannerAd.onLoad(function () {
            if (node == null || !node.active || !node.isValid) {
                return;
            }
            _this.m_BannerAd
                .show()
                .then(function () {
                console.log("广告显示成功");
            })
                .catch(function (err) {
                console.log("广告组件出现问题", err);
            });
        });
        this.m_BannerAd.onError(function (e) {
            _this.bannerSuccess = false;
            console.log("广告显示错误,错误原因：", e);
        });
    };
    TtApi.prototype.hideBanner = function () {
        if (null != this.m_BannerAd) {
            this.m_BannerAd.hide();
        }
    };
    TtApi.prototype.showNativeAd = function () {
    };
    //错误方法
    TtApi.prototype.OnVideoAdError = function (e) {
        console.error('tt 视频广告错误', e);
        //
        var reportData = miniParam_1.getVideoFailLoadOrShow(["" + e.errCode, e.errMsg]);
        this.reportAnalytics(reportData.key, reportData.obj);
    };
    TtApi.prototype.loadAndShowVideoAd = function (successCallback, errorCallback, completeCallback, reportAnalyticsExplain, videoIdPos) {
        //
        var _this = this;
        if (reportAnalyticsExplain === void 0) { reportAnalyticsExplain = '未定义说明'; }
        if (videoIdPos === void 0) { videoIdPos = 0; }
        if (this.wasVideo) {
            return;
        }
        this.wasVideo = true;
        cc.director.pause();
        // successCallback && successCallback();
        // completeCallback && completeCallback();
        // return;
        if (gameConfig_1.default.VIDIOCONTR == 0) {
            cc.director.resume();
            // setTimeout(successCallback,0.1);
            // successCallback && successCallback();
            completeCallback && completeCallback();
            this.wasVideo = false;
            return;
        }
        this.showLoading({ title: '请求中', mask: true });
        //错误上报
        if (this.OnVideoAdErrorCallback == null) {
            this.OnVideoAdErrorCallback = this.OnVideoAdError.bind(this);
        }
        //
        var adUnitId = data_control_1.default.getRandItemOfArray(this.m_adUnitIdList);
        console.log('tt 视频广告', adUnitId, reportAnalyticsExplain);
        //创建 视频
        var videoAd = tt.createRewardedVideoAd({
            adUnitId: adUnitId,
        });
        //监听 视频错误 防止重复监听
        videoAd.offError(this.OnVideoAdErrorCallback);
        videoAd.onError(this.OnVideoAdErrorCallback);
        //监听 视频关闭
        var onCloseVideoAd = function (res) {
            //
            videoAd.offClose(onCloseVideoAd);
            cc.director.resume();
            console.log('tt 视频广告关闭', res);
            if (res && res.isEnded) {
                //上报奖励
                var reportData = miniParam_1.getLookVideoReportData(reportAnalyticsExplain);
                _this.reportAnalytics(reportData.key, reportData.obj);
                // 给予奖励
                successCallback();
            }
            else {
                //上报提前关闭
                var reportLoad_1 = miniParam_1.getBeforeCloseVideoReportData(reportAnalyticsExplain);
                _this.reportAnalytics(reportLoad_1.key, reportLoad_1.obj);
                //
                errorCallback('视频中途退出');
            }
            completeCallback && completeCallback();
            _this.wasVideo = false;
        };
        //展示失败可以重试
        var onTryAgain = function (e) {
            //上报拉取
            var reportLoad = miniParam_1.getLoadVideoReportData(reportAnalyticsExplain);
            _this.reportAnalytics(reportLoad.key, reportLoad.obj);
            //
            videoAd.load().then(function () {
                //上报展示
                var reportLoad = miniParam_1.getShowVideoReportData(reportAnalyticsExplain);
                _this.reportAnalytics(reportLoad.key, reportLoad.obj);
                videoAd.show().then(function () {
                    _this.hideLoading();
                    videoAd.onClose(onCloseVideoAd);
                    //展示异常
                }).catch(function (e) {
                    errorCallback && errorCallback('视频展示异常');
                    cc.director.resume();
                    completeCallback && completeCallback();
                    _this.wasVideo = true;
                });
                //加载异常
            }).catch(function (e) {
                errorCallback && errorCallback('视频拉取异常02');
                cc.director.resume();
                completeCallback && completeCallback();
                _this.wasVideo = true;
            });
        };
        //加载 Promise
        //上报拉取
        // let reportLoad = getLoadVideoReportData(reportAnalyticsExplain);
        // this.reportAnalytics(reportLoad.key, reportLoad.obj);
        //
        // videoAd.load().then(() => {
        //上报展示
        var reportLoad = miniParam_1.getShowVideoReportData(reportAnalyticsExplain);
        this.reportAnalytics(reportLoad.key, reportLoad.obj);
        console.log('展示一次');
        videoAd.show().then(function () {
            _this.hideLoading();
            videoAd.onClose(onCloseVideoAd);
            //展示异常
        }).catch(function (e) {
            console.log('重试一次');
            onTryAgain(e);
        });
        //加载异常
        // }).catch((e) => {
        //     errorCallback && errorCallback('视频拉取异常01');
        //     completeCallback && completeCallback();
        // });
    };
    TtApi.prototype.login = function (params) {
        tt.login(params);
    };
    TtApi.prototype.authorize = function (params) {
        params.success && params.success();
    };
    //
    TtApi.prototype.operateGameLive = function () {
        console.log('tt operateGameLive');
        tt.operateGameLive({
            type: "start",
            success: function (res) {
                console.log("tt operateGameLive success", res);
            },
            fail: function (res) {
                console.log("tt operateGameLive fail", res);
                // ...
            }
        });
        tt.onGameLiveStatusChange(function (res) {
            console.log('tt 直播状态变化', res);
        });
    };
    TtApi.prototype.gameRecordStart = function (params, onStart) {
        var _this = this;
        if (!this.isHaveShareVideo())
            return;
        this.m_gameRecordTimeNow = Date.now();
        this.m_gameRecordVideoUrl = null;
        this.m_gameRecorderManager.onStart(function (res) {
            console.log('tt 录屏开始', res);
            onStart && onStart(res);
        });
        this.m_gameRecorderManager.onStop(function (res) {
            console.log('tt 录屏结束', res.videoPath);
            _this.m_gameRecordVideoUrl = res.videoPath;
        });
        this.m_gameRecorderManager.start(params);
    };
    TtApi.prototype.gameRecordStop = function () {
        if (!this.isHaveShareVideo())
            return false;
        if (Date.now() - this.m_gameRecordTimeNow < 3500) {
            return false;
        }
        this.m_gameRecorderManager.stop();
        return true;
    };
    TtApi.prototype.isGameRecordOver = function () {
        return this.m_gameRecordVideoUrl != null;
    };
    TtApi.prototype.shareGameRecordVideo = function (successCb, failCb) {
        var _this = this;
        if (!this.isHaveShareVideo())
            return;
        if (this.m_gameRecordVideoUrl) {
            tt.shareAppMessage({
                channel: "video",
                title: gameConfig_1.default.GAME_NAME,
                desc: gameConfig_1.default.GAME_VIDEO_SHARE_DESC,
                extra: {
                    hashtag_list: [gameConfig_1.default.GAME_NAME],
                    videoPath: this.m_gameRecordVideoUrl,
                    videoTopics: [gameConfig_1.default.GAME_NAME],
                    video_title: gameConfig_1.default.GAME_VIDEO_SHARE_TITLE,
                    withVideoId: true,
                    defaultBgm: 'https://v.douyin.com/JmcxWo8/',
                },
                success: function (res) {
                    var shareGameRecord = miniParam_1.getShareGameRecordReportData('分享成功');
                    _this.reportAnalytics(shareGameRecord.key, shareGameRecord.obj);
                    console.log("tt 分享视频成功");
                    //
                    console.log(res.videoId);
                    console.log(res.shareWithShareBgmStatus); //回调参数
                    console.log("分享视频成功 4");
                    successCb && successCb();
                },
                fail: function (e) {
                    var shareGameRecord = miniParam_1.getShareGameRecordReportData('分享失败');
                    _this.reportAnalytics(shareGameRecord.key, shareGameRecord.obj);
                    console.log("tt 分享视频失败", e);
                    // modules().uiControlModule.showMessageBox("分享视频时长不能少于3秒");
                    if (e.errMsg == 'shareAppMessage:cancel') {
                        gameEngine_1.modules().uiControlModule.showMessageBox("取消分享");
                    }
                    failCb && failCb(e);
                }
            });
        }
        else {
            failCb && failCb(null);
            gameEngine_1.modules().uiControlModule.showMessageBox("分享视频时长不能少于3秒");
            console.log("tt 分享视频为空");
        }
    };
    //添加桌面
    TtApi.prototype.addShortcut = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            tt.addShortcut({
                success: function () {
                    var ret = miniParam_1.getAddShortcutReportData('添加成功');
                    _this.reportAnalytics(ret.key, ret.obj);
                    resolve(true);
                },
                fail: function () {
                    var ret = miniParam_1.getAddShortcutReportData('添加失败');
                    _this.reportAnalytics(ret.key, ret.obj);
                    resolve(false);
                }
            });
        });
    };
    /**production    线上版
     development    测试版
     preview    预览版
     * */
    TtApi.prototype.isProduction = function () {
        return TtApi.isProduction();
    };
    TtApi.prototype.isHaveShareVideo = function () {
        return true;
    };
    //判断是否合法APP-ID
    TtApi.prototype.validAppId = function () {
        // tt.onShow((res: { query, refererInfo: { appId: string, extraData: {} } }) => {
        //     console.log(res.refererInfo.appId,this.m_appId,"appid对比")
        //     if (res.refererInfo.appId != this.m_appId) {
        //         cc.game.end();
        //         throw '非法盗用此程序将受到法律制裁';
        //     } else {
        //         console.log('tt APP-ID 授权成功');
        //     }
        // });
    };
    TtApi.prototype.reportAnalytics = function (eventKey, data) {
        console.log("tt 发送埋点", eventKey, data);
        tt.reportAnalytics(eventKey, data);
    };
    TtApi.prototype.clearMemory = function () {
    };
    TtApi.prototype.shareAppMessage = function (args) {
    };
    TtApi.prototype.createRewardedVideoAd = function (param) {
        this.m_videoAd = tt.createRewardedVideoAd(param);
    };
    TtApi.prototype.getAccessToken = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve) {
                        //没有就请求
                        if (_this.m_accessToken) {
                            resolve(_this.m_accessToken);
                            return;
                        }
                        //
                        var url = "https://developer.toutiao.com/api/apps/token?appid=" + _this.m_appId + "&secret=" + _this.m_secret + "&grant_type=client_credential";
                        tt.request({
                            url: url,
                            success: function (res) {
                                if (res.statusCode != 200) {
                                    console.error('#652错误 获取Access_token状态错误', res.errMsg, res);
                                    resolve(null);
                                    return;
                                }
                                _this.m_accessToken = res.data.access_token;
                                resolve(_this.m_accessToken);
                            },
                            fail: function (err) {
                                console.error('#654错误 获取access_token失败', err);
                                resolve(null);
                            }
                        });
                    })];
            });
        });
    };
    /**production    线上版
     development    测试版
     preview    预览版
     * */
    TtApi.isProduction = function () {
        return tt.env.VERSION == 'production';
    };
    TtApi.prototype.reportAdClickNativeAd = function () {
    };
    TtApi.prototype.getShareVideoRank = function (sortType, successCb) {
        var _this = this;
        this.getAccessToken().then(function (accessToken) {
            console.log('当前token', accessToken);
            var url = '';
            switch (sortType) {
                case miniApp_1.SHARE_VIDEO_SORT_TYPE.HOT: {
                    url = 'https://gate.snssdk.com/developer/api/get_top_video_ids_by_like';
                    break;
                }
                case miniApp_1.SHARE_VIDEO_SORT_TYPE.TIME: {
                    url = 'https://gate.snssdk.com/developer/api/get_top_video_ids_by_time';
                    break;
                }
                default: {
                    console.error('#661 错误获取排行排序类型错误');
                    return;
                }
            }
            //
            tt.request({
                url: url,
                method: "POST",
                data: {
                    app_id: _this.m_appId,
                    number_of_top: 20,
                    // tag: "testTag1", //分享视频时传入videoTag情况下，用于筛选指定tag视频
                    access_token: accessToken,
                },
                success: function (res) {
                    console.log("排行榜信息", res.data);
                    if (res.statusCode != 200) {
                        console.error('#725 错误的排行榜', res.statusCode, res.errMsg, res);
                        return;
                    }
                    if (res.data) {
                        successCb(res.data.data);
                    }
                    successCb([]);
                    // 从res中获取所需视频信息（videoId数组索引与返回数据数组索引一一对应）
                },
                fail: function (err) {
                    console.error('#736错误 ', err);
                    tt.showToast({ title: '请求超时' });
                    successCb([]);
                }
            });
        }).catch(function (e) {
            console.error('#706 异常', e);
            successCb([]);
        });
    };
    TtApi.prototype.drawUrlImage = function (url, overCb) {
        var image = tt.createImage();
        image.src = url;
        console.log("tt 加载图片", url);
        image.addEventListener("load", function (res) {
            console.log("tt 加载成功 RGBA8888", res);
            if (res && res.target && res.target.data) {
                var texture = new cc.Texture2D();
                texture.initWithElement(image /*res.target.data, cc.Texture2D.PixelFormat.RGBA8888, res.target.width, res.target.height*/);
                texture.handleLoadedTexture();
                var spf = new cc.SpriteFrame(texture);
                overCb(spf);
            }
        });
        image.addEventListener("error", function (res) {
            console.error("tt 图片加载失败", res);
        });
    };
    TtApi.prototype.showVideo = function (videoUrl) {
        console.log('tt 播放视频', videoUrl);
        //播放视频
        tt.navigateToVideoView({
            videoId: videoUrl,
            success: function (res) {
                /* res结构： {errMsg: string } */
                console.log("tt done", res);
            },
            fail: function (err) {
                switch (err.errCode) {
                    case 1002: {
                        tt.showToast({ title: '视频被删除' });
                        break;
                    }
                }
                console.error('#772 播放错误', err);
            },
        });
    };
    TtApi.prototype.subscribeMessage = function (successCallback, failCallback, completeCallback) {
        var _this = this;
        tt.requestSubscribeMessage({
            tmplIds: ['MSG11613335c650b014f0bcdffad5afb4c8cb0354113715'],
            success: function (res) {
                //订阅成功
                console.log("订阅成功", res);
                _this.showToast({ title: '订阅成功' });
                successCallback && successCallback();
            },
            fail: function (error) {
                //订阅失败
                console.log("订阅失败, 错误详情:", error);
                _this.showToast({
                    title: "订阅失败",
                    icon: "fail",
                });
                failCallback && failCallback();
            },
            complete: function (res) {
                //订阅完成
                console.log("tt.requestSubscribeMessage API调用完成: ", res);
                completeCallback && completeCallback();
            },
        });
    };
    TtApi.prototype.showAddFavoriteGuide = function (successCallback, failCallback, completeCallback) {
        tt.showFavoriteGuide({
            content: "一键添加到我的小程序",
            success: function (res) {
                console.log("引导组件展示成功");
                successCallback && successCallback();
            },
            fail: function (res) {
                console.warn("引导组件展示失败", res);
                failCallback && failCallback();
            },
            complete: function (res) {
                completeCallback && completeCallback();
            }
        });
    };
    TtApi.prototype.StartRecordSound = function () {
        if (this.m_soundRecordManager == null) {
            this.m_soundRecordManager = tt.getRecorderManager();
        }
        this.m_soundRecordManager.onError(function (e) {
            console.error('tt 录音错误', e.errMsg, e);
        });
        this.m_soundRecordManager.onStart(function () {
            console.log('tt 录音已开始');
        });
        //
        console.log('tt 开始录音');
        this.m_soundRecordManager.start({
            duration: 60000,
            sampleRate: 44100,
            numberOfChannels: 2,
            encodeBitRate: 128000,
            frameSize: 8000,
        });
    };
    TtApi.prototype.StopRecordSound = function (successCallback) {
        var _this = this;
        console.log('tt 结束录音');
        //
        this.m_soundRecordManager.onStop(function (res) {
            console.log('tt 录音已结束', res.tempFilePath);
            _this.m_lastRecordSoundPath = res.tempFilePath;
            successCallback && successCallback();
        });
        //
        this.m_soundRecordManager.stop();
    };
    TtApi.prototype.getChangeAudioBuffer = function (srcBuffer, scale) {
        var ctx = tt.getAudioContext();
        var buf = ctx.createBuffer(srcBuffer.numberOfChannels, srcBuffer.length * scale, srcBuffer.sampleRate);
        console.log('tt 变声可以在这执行 源长', srcBuffer.length, scale);
        for (var channel = 0; channel < buf.numberOfChannels; channel++) {
            var arr = buf.getChannelData(channel);
            var srcArr = srcBuffer.getChannelData(channel);
            console.log('tt 变声可以在这执行 目标长', buf.length);
            for (var i = 0; i < buf.length; i++) {
                arr[i] = srcArr[Math.floor(i / scale)];
            }
        }
        return buf;
    };
    TtApi.prototype.PlayLastRecordSound = function (scale, successCb, errorCb) {
        var _this = this;
        if (!this.m_lastRecordSoundPath) {
            console.error('#918错误 未有的数据');
            errorCb && errorCb();
        }
        //
        scale = scale || 1;
        console.log('tt 播放变音 2', scale);
        //
        var fileSystemManager = tt.getFileSystemManager();
        fileSystemManager.readFile({
            filePath: this.m_lastRecordSoundPath,
            success: function (res) {
                console.log('tt 文件读取成功', res);
                // 播放
                var ctx = tt.getAudioContext();
                console.log('tt 开始解析', res.data);
                ctx.decodeAudioData(res.data).then(function (audioBuffer) {
                    var buf = _this.getChangeAudioBuffer(audioBuffer, scale);
                    console.log('tt 播放', buf);
                    var source = ctx.createBufferSource();
                    source.buffer = buf;
                    // source.playbackRate.value = 1 / scale;
                    source.connect(ctx.destination);
                    source.start();
                    source.onended = function () {
                        console.log("tt 播放结束", this);
                        successCb && successCb();
                    };
                }).catch(function (err) {
                    console.error("解码出错", err.name, err.message, err.code);
                    console.error("解码出错 JSON", JSON.stringify(err));
                    errorCb && errorCb();
                });
            },
            fail: function (e) {
                errorCb && errorCb();
                console.error('#927 文件读取错误', JSON.stringify(e));
            }
        });
    };
    TtApi.prototype.playerOnlineSound = function (tempo, pitch) {
        console.log('播放在线音频 14');
        //  创建一个 AudioContext
        var ctx = tt.getAudioContext();
        var request = new XMLHttpRequest();
        request.open("GET", 'http://hao.haolingsheng.com/ring/000/991/86ced5cdc9783286406185bc0738502e.mp3', true);
        /*"http://hao.haolingsheng.com/ring/000/992/833a6bfabfbde371ab75ed77c1960b53.mp3"*/
        /*http://hao.haolingsheng.com/ring/000/993/7bff75924dab3ade43248b3f4a132125.mp3*/
        request.responseType = "arraybuffer";
        //
        request.onload = function () {
            var audioData = request.response;
            console.log('收到了');
            console.log('解析在线数据', audioData);
            ctx
                .decodeAudioData(audioData)
                .then(function (audioBuffer) {
                console.log(audioBuffer);
                var source = ctx.createBufferSource();
                //
                source.buffer = audioBuffer;
                source.connect(ctx.destination);
                if (tempo == 0.5) {
                    //start
                    //end
                }
                source.start();
                source.onended = function () {
                    console.log("onended called", this);
                };
            })
                .catch(function (err) {
                console.error("解码出错", err);
            });
        };
        request.send();
    };
    TtApi.prototype.CheckLocalToBlockCityList = function () {
        this.m_localInBlockCity = false;
    };
    TtApi.prototype.LocalInBlockCityList = function () {
        return this.m_localInBlockCity;
    };
    TtApi.prototype.vibrate = function (type) {
        switch (type) {
            case miniApp_1.VIBRATE_TYPE.LONG: {
                tt.vibrateLong();
                break;
            }
            case miniApp_1.VIBRATE_TYPE.SHORT: {
                tt.vibrateShort();
                break;
            }
        }
    };
    TtApi.prototype.commitRank = function (score) {
        return __awaiter(this, void 0, Promise, function () {
            return __generator(this, function (_a) {
                // console.debug('tt 提交分数 1');
                // if (!await this.isAntherUserInfo()) {
                //     console.debug('tt 尚未授权');
                //     if (!await this.goLoginSelect('提交排行榜分数')) {
                //         console.debug('tt 授权失败');
                //         this.showToast({title: '用户授权失败'});
                //         return Promise.resolve(false);
                //     }
                //     console.debug('tt 授权成功');
                // }
                // //设置分组
                // tt.setUserGroup({
                //     groupId: dataField.RANK_GROUP.TT_USER
                // });
                // //提交排行榜
                // const option = <dataField.RankInterface>{};
                // option.score = score;
                // option.rankId = rankId;
                // option.operaType = dataField.OPERA_TYPE.COMMIT_SCORE;
                // tt.getOpenDataContext().postMessage(option);
                // return Promise.resolve(true);
                return [2 /*return*/, new Promise(function (resolve) {
                        if (tt.setImRankData) {
                            tt.setImRankData({
                                dataType: 0,
                                value: score.toString(),
                                priority: 0,
                                extra: "extra",
                                success: function (res) {
                                    console.log("setImRankData success res: " + res);
                                    resolve(true);
                                },
                                fail: function (res) {
                                    console.log("setImRankData fail res: " + res.errMsg);
                                    resolve(false);
                                },
                            });
                        }
                        else {
                            console.log("设置排行榜分数错误,头条版本号过低");
                            resolve(false);
                        }
                    })];
            });
        });
    };
    TtApi.prototype.showRank = function () {
        return __awaiter(this, void 0, Promise, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.isAntherUserInfo()];
                    case 1:
                        if (!!(_a.sent())) return [3 /*break*/, 3];
                        console.debug('tt 尚未授权');
                        return [4 /*yield*/, this.goLoginSelect('提交排行榜分数')];
                    case 2:
                        if (!(_a.sent())) {
                            console.debug('tt 授权失败');
                            this.showToast({ title: '用户授权失败' });
                            return [2 /*return*/, Promise.resolve(false)];
                        }
                        console.debug('tt 授权成功');
                        _a.label = 3;
                    case 3: return [2 /*return*/, new Promise(function (resolve) {
                            if (tt.getImRankList) {
                                tt.getImRankList({
                                    relationType: "default",
                                    dataType: 0,
                                    rankType: "all",
                                    suffix: "关",
                                    rankTitle: "排行榜",
                                    success: function (res) {
                                        console.log("getImRankData success res: " + JSON.stringify(res));
                                        resolve(true);
                                    },
                                    fail: function (res) {
                                        console.log("getImRankData fail res: " + res.errMsg);
                                        resolve(true);
                                    },
                                });
                            }
                            else {
                                console.log("展示排行榜错误  头条基础版本库不支持API");
                                resolve(false);
                            }
                        })];
                }
            });
        });
    };
    //选择登录失败
    TtApi.prototype.goLoginSelect = function (title) {
        return __awaiter(this, void 0, Promise, function () {
            var _this = this;
            return __generator(this, function (_a) {
                //
                console.debug('tt 授权弹提示框');
                return [2 /*return*/, new Promise(function (resolve) {
                        _this.showModal({
                            title: title,
                            content: '此功能需要授权登录账号才可使用',
                            confirmText: '登录',
                            cancelText: '取消',
                            showCancel: true,
                            success: function (result) {
                                console.debug('tt 授权弹提示框完毕');
                                //选择登录
                                if (result.confirm) {
                                    console.debug('tt 拉起登录');
                                    //
                                    _this.login({
                                        force: true,
                                        success: function (res) {
                                            console.debug('tt 登录完成 1');
                                            // this.m_currLoginCode = res.code;
                                            //可先调用拉起设置
                                            // tt.openSetting({
                                            //     success:(res) => {
                                            //         console.log(res);
                                            //     },
                                            //     fail:(res) => {
                                            //         console.log(`openSetting 调用失败`);
                                            //     },
                                            // });
                                            //授权
                                            _this.authorize({
                                                scope: "scope.userInfo",
                                                success: function () {
                                                    console.debug('tt 授权成功');
                                                    //信息获取
                                                    _this.getUserInfo({
                                                        success: function (res) {
                                                            console.debug('tt 获取用户信息成功');
                                                            resolve(true);
                                                        },
                                                        fail: function () {
                                                            resolve(false);
                                                        }
                                                    });
                                                },
                                                fail: function () {
                                                    resolve(false);
                                                }
                                            });
                                            // //获取唯一ID
                                            // if (this.m_UniqueId) {
                                            //     return;
                                            // }
                                            // //
                                            // gameHttp_module.getUserWxIdentifyByCode(this.m_currLoginCode, (res) => {
                                            //     console.debug('我的唯一ID', res);
                                            //     this.m_UniqueId = res;
                                            //     gameHttp_module.getUserWebInfo(this.m_UniqueId, (res) => {
                                            //         this.m_curWebUserInfo = JSON.parse(res);
                                            //         console.debug('读取到的数据', res);
                                            //         this.onWebInfoGetOnce();
                                            //     }, res1 => {
                                            //         this.m_curWebUserInfo = {
                                            //             m_coins: this.m_normalCoins,
                                            //             m_devilCurrLevel: 0,
                                            //             m_synthesisEquipmentList: [],
                                            //             m_unlockStamp: 0,
                                            //         }
                                            //     });
                                            // })
                                        },
                                        fail: function () {
                                            resolve(false);
                                        }
                                    });
                                }
                                else {
                                    resolve(false);
                                }
                            }, fail: function () {
                                resolve(false);
                            }
                        });
                    })];
            });
        });
    };
    TtApi.prototype.isAntherUserInfo = function () {
        return __awaiter(this, void 0, Promise, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve) {
                        tt.getSetting({
                            //Function		否	接口调用成功的回调函数	1.3.0
                            success: function (res) {
                                console.debug('tt 设置结果', res);
                                resolve(res.authSetting["scope.userInfo"]);
                            },
                            //
                            fail: function () {
                                resolve(false);
                            },
                        });
                    })];
            });
        });
    };
    TtApi.prototype.navigateToMiniGame = function (appId, successCallback, failCallback) {
        console.error('#1000102904 未实现跳转');
    };
    return TtApi;
}(miniApp_1.default));
exports.default = TtApi;
/**
 //均衡器
 const equalizer = ctx.createEqualizer();
 // 或者ctx.createEqualizer(7.0, -8.0, 9.6, 9.6, 5.6, 1.6, -4.0, -8.0, -10.4, -11.2, -11.2)
 equalizer.setAMPs(
 7.0,
 -8.0,
 9.6,
 9.6,
 5.6,
 1.6,
 -4.0,
 -8.0,
 -10.4,
 -11.2,
 -11.2
 );
 source.connect(equalizer);
 equalizer.connect(ctx.destination);
 */
/**
 //start 混响
 const reverb = ctx.createReverb();
 //KTV 效果 一些常见参数可以参考ReverbNode节点内容
 reverb.roomSize = 1.17;
 reverb.damping = 0.89;
 reverb.stereoDepth = 0.86;
 reverb.dry = 1.6;
 reverb.wet = 0.41;
 source.connect(reverb);
 reverb.connect(ctx.destination);
 //end
 */

cc._RF.pop();